package com.xzit.day03.controller;

import com.xzit.day03.model.Student;
import com.xzit.day03.model.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TeacherController {

    @Autowired
    private Teacher teacher;

    // 1.显示教师信息
    @GetMapping("/teacher")
    public Teacher getTeacher() {
        return teacher;
    }

    // 2.显示每个学生的三科平均成绩(流式编程)
    @GetMapping("/students/average")
    public Map<String, Double> getStudentAverages() {
        Map<String, Double> result = new HashMap<>();
        for (Student s : teacher.getStudents()) {
            double avg = s.getScores().values().stream().mapToInt(Integer::intValue).average().orElse(0);
            //保留两位小数
            avg = (double) Math.round(avg * 100) / 100;
            result.put(s.getName(), avg);
        }
        return result;
    }

    // 3.显示语文平均成绩
    @GetMapping("/chinese/average")
    public double getChineseAverage() {
        double avg = teacher.getStudents().stream()
                .mapToInt(s -> s.getScores().get("chinese"))
                .average().orElse(0);
        //保留两位小数
        avg = (double) Math.round(avg * 100) / 100;
        return avg;
    }

}
